package com.lwl.shua.class02;

/**
 * @author lwl
 * @Description TODO
 * @date 2025/9/6 17:10
 */
public class Code06Lc581FindUnsortedSubarray {

    public int findUnsortedSubarray(int[] nums) {
        int leftMax = nums[0];
        // 最右边不满足从大到小的下标
        int mostRight = 0;
        for (int i = 1; i < nums.length; i++) {
            if (leftMax <= nums[i]) {
                leftMax = nums[i];
            } else {
                mostRight = i;
            }
        }
        if (mostRight == 0) {
            return 0;
        }
        int rightMin = nums[nums.length - 1];
        int mostLeft = nums.length - 1;
        for (int i = nums.length - 2; i >= 0; i--) {
            if (rightMin >= nums[i]) {
                rightMin = nums[i];
            } else {
                mostLeft = i;
            }
        }
        return mostRight - mostLeft + 1;
    }

}
